<template>
  <div class="my-new-finance">
    <v-dialog :title="isAdd ? '新增' : '编辑'" :show.sync="dialogVisible" width="1200px" @beforeClose="beforeClose" :close-on-click-modal="false">
      <div class="card-box">
        <div class="card-title">工程信息</div>
        <el-form ref="information" :model="projectForm.information" class="form-wrap" size="small" :rules="information_rules" label-position="top">
          <el-form-item label="工程名称" prop="projectName">
            <el-input
              readonly
              suffix-icon="el-icon-search"
              v-model="projectForm.information.projectName"
              maxlength="100"
              placeholder="请输入工程名称"
              @click.native="handleClickProjectName"
            ></el-input>
          </el-form-item>
          <el-form-item label="工程地址" prop="projectAddress">
            <el-input readonly v-model="projectForm.information.projectAddress" maxlength="100" placeholder="请输入工程地址"></el-input>
          </el-form-item>
          <el-form-item label="工程类型" prop="projectType">
            <el-input readonly v-model="projectForm.information.projectType" maxlength="100" placeholder="请输入工程类型"></el-input>
          </el-form-item>
        </el-form>
        <div class="card-title">项目建议书信息</div>
        <el-form ref="proposal" :model="projectForm.proposal" class="form-wrap" size="small" :rules="proposal_rules" label-position="top">
          <el-form-item label="文号" prop="proposalDocument">
            <el-input v-model="projectForm.proposal.proposalDocument" maxlength="50" placeholder="请输入文号"></el-input>
          </el-form-item>
          <el-form-item label="金额(元)" prop="proposalAmount">
            <el-input v-model="projectForm.proposal.proposalAmount" maxlength="18" placeholder="请输入金额"></el-input>
          </el-form-item>
          <el-form-item label="审批日期" prop="proposalApprove">
            <el-date-picker v-model="projectForm.proposal.proposalApprove" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="请选择审批日期"></el-date-picker>
          </el-form-item>
        </el-form>
        <div class="card-title">可行性研究报告信息</div>
        <el-form ref="feasibility" :model="projectForm.feasibility" class="form-wrap" size="small" :rules="feasibility_rules" label-position="top">
          <el-form-item label="文号" prop="feasibleDocument">
            <el-input v-model="projectForm.feasibility.feasibleDocument" maxlength="50" placeholder="请输入文号"></el-input>
          </el-form-item>
          <el-form-item label="金额(元)" prop="feasibleAmount">
            <el-input v-model="projectForm.feasibility.feasibleAmount" maxlength="18" placeholder="请输入金额"></el-input>
          </el-form-item>
          <el-form-item label="审批日期" prop="feasibleApprove">
            <el-date-picker v-model="projectForm.feasibility.feasibleApprove" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="请选择审批日期"></el-date-picker>
          </el-form-item>
        </el-form>
        <div class="card-title">概算批复文件</div>
        <el-form ref="Estimate" :model="projectForm.Estimate" class="form-wrap" size="small" :rules="Estimate_rules" label-position="top">
          <el-form-item label="文号" prop="estimateDocument">
            <el-input v-model="projectForm.Estimate.estimateDocument" maxlength="50" placeholder="请输入文号"></el-input>
          </el-form-item>
          <el-form-item label="金额(元)" prop="estimateAmount">
            <el-input v-model="projectForm.Estimate.estimateAmount" maxlength="18" placeholder="请输入金额"></el-input>
          </el-form-item>
          <el-form-item label="审批日期" prop="estimateApprove">
            <el-date-picker v-model="projectForm.Estimate.estimateApprove" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="请选择审批日期"></el-date-picker>
          </el-form-item>
        </el-form>
        <div class="card-title">预算审核文件</div>
        <el-form ref="budget" :model="projectForm.budget" class="form-wrap" size="small" :rules="budget_rules" label-position="top">
          <el-form-item label="文号" prop="budgetDocument">
            <el-input v-model="projectForm.budget.budgetDocument" maxlength="50" placeholder="请输入文号"></el-input>
          </el-form-item>
          <el-form-item label="金额(元)" prop="budgetAmount">
            <el-input v-model="projectForm.budget.budgetAmount" maxlength="18" placeholder="请输入金额"></el-input>
          </el-form-item>
          <el-form-item label="审批日期" prop="budgetApprove">
            <el-date-picker v-model="projectForm.budget.budgetApprove" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="请选择审批日期"></el-date-picker>
          </el-form-item>
        </el-form>
        <div class="card-title">附件</div>
        <div class="handling-opinions">
          <v-upload
            ref="informationUpload"
            :busId="projectForm.information.projectSetupId"
            modelType="information"
            @onSuccess="onSuccess"
            isShowFileList
            :isView="false"
            multiple
            v-model="fileList"
          />
        </div>
      </div>
      <span slot="foot">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button v-throttle="[commit]">保 存</el-button>
      </span>
    </v-dialog>
    <v-dialog title="请选择工程名称" :show.sync="projectDialogVisible" :close-on-click-modal="false" width="1000px">
      <div style="padding: 5px">
        <dataList :pageInfo="pager" :listData="tableData" placeholder="请输入工程名称" searchName="projectName" :menuList="[]">
          <el-table :data="tableData">
            <el-table-column label="工程名称" prop="projectName"></el-table-column>
            <el-table-column label="工程地址" prop="projectAddress"></el-table-column>
            <el-table-column label="工程类型" prop="projectType" width="100">
              <template slot-scope="scope">{{getCardTypeValue(scope.row.projectType,projectTypes)}}</template>
            </el-table-column>
            <el-table-column label="单位联系人" prop="agentContact" width="100"></el-table-column>
            <el-table-column label="联系电话" prop="agentPhone" width="120"></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="text" @click="handleClickAdd(scope.row)">选择名称</el-button>
              </template>
            </el-table-column>
          </el-table>
        </dataList>
      </div>
    </v-dialog>
  </div>
</template>

<script>
import BaseLoad from '@/assets/vue-mixin/BaseLoad'
import { doubleValidate } from '~/utils/validate.js'
import { save, update, get, validateCode, queryProject } from '../api/information'
export default {
  name: "edit-data",
  created () {
    this.projectTypes = this.getDict('epc_project_type')
  },
  provide () {
    return {
      initList: this.getProjectNameList
    };
  },
  beforeMount () {
    this.getProjectNameList()
  },
  mixins: [BaseLoad],
  data () {
    let validateSymbol = (rule, value, callback) => {
      if (!value) {
        callback()
      }
      this.validateOnly(rule, value, callback)
    };
    return {
      dialogVisible: false,
      projectDialogVisible: false,
      isAdd: true,
      symbolType: '',
      projectForm: {
        information: {
          projectId: '',
          projectSetupId: '',
          projectName: '',
          projectAddress: '',
          projectType: ''
        },
        proposal: {
          proposalDocument: '',
          proposalAmount: '',
          proposalApprove: ''
        },
        feasibility: {
          feasibleDocument: '',
          feasibleAmount: '',
          feasibleApprove: ''
        },
        Estimate: {
          estimateDocument: '',
          estimateAmount: '',
          estimateApprove: ''
        },
        budget: {
          budgetDocument: '',
          budgetAmount: '',
          budgetApprove: ''
        }
      },
      registrationForm: {},
      projectTypes: [],
      fileList: [],
      params: {
        current: 1,
        size: 10,
        projectName: ""
      },
      pager: {
        total: 0, // 总页数
        current: 1, // 当前页数
        size: 10 // 每页显示多少条
      },
      //表单数据
      tableData: [],
      information_rules: {
        projectName: [{ required: true, message: '请输入工程名称', trigger: 'change' }],
        projectAddress: [{ required: true, message: '请输入工程地址', trigger: 'blur' }],
        projectType: [{ required: true, message: '请选择工程类型', trigger: 'blur' }]
      },
      proposal_rules: {
        proposalAmount: [{ required: false, message: '请输入金额', trigger: 'blur' },
        { validator: doubleValidate, trigger: "blur" }],
        proposalDocument: [{ required: false, message: '请输入文号', trigger: 'blur' },
        { validator: validateSymbol, trigger: "blur" }],
      },
      feasibility_rules: {
        feasibleAmount: [{ required: false, message: '请输入金额', trigger: 'blur' },
        { validator: doubleValidate, trigger: "blur" }],
        feasibleDocument: [{ required: false, message: '请输入文号', trigger: 'blur' },
        { validator: validateSymbol, trigger: "blur" }],
      },
      Estimate_rules: {
        estimateAmount: [{ required: false, message: '请输入金额', trigger: 'blur' },
        { validator: doubleValidate, trigger: "blur" }],
        estimateDocument: [{ required: false, message: '请输入文号', trigger: 'blur' },
        { validator: validateSymbol, trigger: "blur" }],
      },
      budget_rules: {
        budgetAmount: [{ required: false, message: '请输入金额', trigger: 'blur' },
        { validator: doubleValidate, trigger: "blur" }],
        budgetDocument: [{ required: false, message: '请输入文号', trigger: 'blur' },
        { validator: validateSymbol, trigger: "blur" }],
      }
    }
  },
  methods: {
    //打开弹框
    show (item) {
      this.dialogVisible = true
      if (item) {
        this.isAdd = false
        this.projectForm.information.projectSetupId = item
        get(item).then(res => {
          if (res.data.code === 0 && res.data.data.epcProjectSetup !== null) {
            this.projectForm.information = res.data.data.epcProjectSetup
            this.projectForm.proposal = res.data.data.epcProjectSetup
            this.projectForm.feasibility = res.data.data.epcProjectSetup
            this.projectForm.Estimate = res.data.data.epcProjectSetup
            this.projectForm.budget = res.data.data.epcProjectSetup
            this.projectForm.information.projectType = this.getCardTypeValue(res.data.data.epcProjectSetup.projectType, this.projectTypes)
          } else {
            this.$message.warning('暂未获取到数据！')
          }
        })
      }
    },
    //关闭弹框
    beforeClose (done) {
      this.$emit('beforeClose')
    },
    //取消
    handleCancel () {
      this.$emit('handleClose')
      this.dialogVisible = false
    },
    //保存
    commit () {
      const information = new Promise((resolve, reject) => {
        this.$refs['information'].validate((valid) => {
          if (valid) resolve();
        })
      })
      const proposal = new Promise((resolve, reject) => {
        this.$refs['proposal'].validate((valid) => {
          if (valid) resolve();
        })
      })
      const feasibility = new Promise((resolve, reject) => {
        this.$refs['feasibility'].validate((valid) => {
          if (valid) resolve();
        })
      })
      const Estimate = new Promise((resolve, reject) => {
        this.$refs['Estimate'].validate((valid) => {
          if (valid) resolve();
        })
      })
      const budget = new Promise((resolve, reject) => {
        this.$refs['budget'].validate((valid) => {
          if (valid) resolve();
        })
      })
      Promise.all([information, proposal, feasibility, Estimate, budget]).then(() => {
        this.registrationForm = {
          ...this.projectForm.information,
          ...this.projectForm.proposal,
          ...this.projectForm.feasibility,
          ...this.projectForm.Estimate,
          ...this.projectForm.budget
        }
        this.$refs.informationUpload.submit();
      })
    },
    //文件上传
    onSuccess (response, file, fileList) {
      //文件上传成功，开始保存表单
      if (fileList !== undefined && fileList.length > 0) {
        if (response.data) {
          this.registrationForm.projectSetupId = response.data
          this.saveFormData(response.data)
        } else {
          this.err('文件上传失败')
        }
      } else {
        this.saveFormData(response.data)
      }
    },
    saveFormData () {
      if (this.registrationForm.projectType === 'EPC') {
        this.registrationForm.projectType = '20'
      } else {
        this.registrationForm.projectType = '10'
      }
      this.loadAction('数据加载中')
      if (this.isAdd) {
        save(this.registrationForm).then((rep) => {
          this.loadClose()
          this.$message.success("保存成功");
          this.dialogVisible = false
          this.$emit('resetList')
        }).catch((e) => {
          this.loadClose()
          this.$message.error("保存失败");
        })
      } else {
        update(this.registrationForm).then((rep) => {
          this.loadClose()
          this.$message.success("修改成功");
          this.dialogVisible = false
          this.$emit('resetList')
        }).catch((e) => {
          this.loadClose()
          this.$message.error("修改失败");
        });
      }
    },
    //验证文号是否存在
    validateOnly (rule, value, callback) {
      if (rule.field === 'proposalDocument') {
        this.symbolType = '1'
      } else if (rule.field === 'feasibleDocument') {
        this.symbolType = '2'
      } else if (rule.field === 'estimateDocument') {
        this.symbolType = '3'
      } else if (rule.field === 'budgetDocument') {
        this.symbolType = '4'
      }
      validateCode({ "projectId": this.projectForm.information.projectId, "vType": this.symbolType, "id": this.projectForm.information.projectSetupId, "code": value }).then(rep => {
        let vr = rep.data.data
        if (vr === 0) {
          return callback();
        } else {
          return callback(new Error("文号不能重复"));
        }
      })
    },
    //选择工程名称
    handleClickProjectName () {
      this.projectDialogVisible = true
    },
    //  * 查询列表
    getProjectNameList (params = {}) {
      this.loading = true
      let requestData = { ...this.params, ...params }
      queryProject(requestData).then(res => {
        const { current, size, total, records } = res.data.data
        this.tableData = records
        this.params = requestData
        this.pager = { total, current, size }
      }).catch(error => {
        this.$message({
          type: "error",
          message: "查询失败"
        });
      }).finally(() => (this.loading = false))
    },
    //工程名称确定
    handleClickAdd (item) {
      if (this.projectForm.information.projectName) {
        this.$confirm('一次只能添加一条数据，该操作将覆盖上条数据,是否继续?', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        }).then(() => {
          this.projectForm.information = item
          this.projectForm.information.projectType = this.getCardTypeValue(item.projectType, this.projectTypes)
          this.$message.success('添加成功！')
          this.projectDialogVisible = false
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      } else {
        this.projectForm.information = item
        this.projectForm.information.projectType = this.getCardTypeValue(item.projectType, this.projectTypes)
        this.$message.success('添加成功！')
        this.projectDialogVisible = false
      }
    },
    //对应value取label
    getCardTypeValue (num, sum) {
      let arr = sum.filter(e => e.value === num)
      if (arr.length > 0) {
        return arr[0].label
      } else {
        return num
      }
    }
  }
}
</script>

<style scoped lang='scss'>
@include formWrap(3);
.handling-opinions {
  padding: 20px;
}
</style>
